
import axios from "axios";
import router from "@/router/index";
import { useUserStore } from "@/store/user";

const http = axios.create({
  // @ts-ignore
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 20000
});

http.interceptors.request.use((config) => {
  const store = useUserStore();
  if (store.token) {
    // 后端返回已经包含 Bearer，则直接透传
    config.headers = config.headers || {};
    config.headers["Authorization"] = store.token;
  }
  return config;
});

http.interceptors.response.use(
  (resp) => {
    if(resp.data.code === 200) {
      return resp.data;
    }else {
      ElMessage.error(resp.data.msg || "请求失败");
      return Promise.reject(resp.data);
    }
  },
  (error) => {
    const status = error?.response?.status;
    if (status === 401) {
      router.replace({ path: "/401" });
    }
    return Promise.reject(error);
  }
);

export default http;
